#!/usr/local/bin/python

import sys,os,time,string,signal
import random
import telnetlib
import l3dgecomms
import elementtree.ElementTree
import getstats
from getstats import Entity
from getstats import Cluster
from getstats import Host
from getstats import Client
from elementtree import ElementTree

#LAMS server
LAMS_IP="136.186.229.114"
LAMS_PORT=27960
LAMS_CONF="lams.conf"
POLL_TIME=30 #seconds

#ganglia
GMETAD_IP="localhost"
GMETAD_PORT=8651

#Entity typesm
ENTITY_SUMMARY="SUMMARY"
ENTITY_SERVER="SERVER"
ENTITY_ASTERISK="ASTERISK"
ENTITY_CLIENT="CLIENT"

def sigHandler(signum, frame):
	print "Got signal " + str(signum)
	l3dgecomms.closeComms()
	print "Connection closed"
	sys.exit()
signal.signal(signal.SIGINT, sigHandler)

#setup l3dgecomms to talk to out LAMS server host
l3dgecomms.setupComms(None,0,LAMS_IP,LAMS_PORT)
print "Connected to LAMS"

#read config file to get hosts
clusters={}
hosts={}
lamsconf=open(LAMS_CONF,'r')
for line in lamsconf:	
	name=string.split(line)[0]
	parentName=string.split(line)[1]
	type=string.split(line)[2]
	id=string.split(line)[3]
	adminWeight=string.split(line)[4]
	
	if type == ENTITY_SUMMARY:
		cluster = Cluster()
		cluster.entity = Entity(name, parentName, type, id, adminWeight)
		clusters[name] = cluster
		
	elif type == ENTITY_SERVER:
		#create host
		host = Host()
		host.serverEntity = Entity(name, parentName, type, id, adminWeight)
		hosts[name] = host
		#add to cluster
		parentClust = clusters[parentName]
		parentClust.hosts[name] = host
		
	elif type == ENTITY_ASTERISK:
		#find host
		host = hosts[parentName]
		host.asteriskEntity = Entity(name, parentName, type, id, adminWeight)
		
	elif type == ENTITY_CLIENT:
		#create client
		client = Client()
		client.entity = Entity(name, parentName, type, id, adminWeight)
		#add to parent host
		host = hosts[parentName]
		host.clientPool.append(client)
		

#start the infinite loop, repeat every POLL_TIME seconds
go=True
while go:
	#get latest xml stats file
	tn = telnetlib.Telnet(GMETAD_IP, GMETAD_PORT)
	xmlData=tn.read_all()
	tn.close()
	#write to file
	file=open("tmp.xml","w")
	file.write(xmlData)
	file.close()
	
	#parse xml
	dataTree=ElementTree.parse("tmp.xml")
	for element in dataTree.getiterator("CLUSTER"):
		try:
			#get the cluster object for xml node
			cluster = clusters[element.attrib["NAME"]]
			print "found cluster " + element.attrib["NAME"]
			cluster.clearMetrics()
			cluster.doMetrics(element)
			cluster.updateLAMS()
			break
		except KeyError:
			print "Could not find cluster " + element.attrib["NAME"]
	
	#do it all again later.
	#go=True
	print "Waiting..."
	time.sleep(POLL_TIME)

#And were done
l3dgecomms.closeComms()
print "Connection closed"